package top.lyc829.zzl_android.ui.thing.follow;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.xuexiang.xui.adapter.recyclerview.XRecyclerAdapter;
import com.xuexiang.xui.widget.imageview.nine.NineGridImageView;
import com.xuexiang.xui.widget.imageview.nine.NineGridImageViewAdapter;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.imageview.preview.loader.GlideMediaLoader;

import java.util.ArrayList;
import java.util.List;

import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.bean.ImageViewInfo;
import top.lyc829.zzl_android.logic.util.Utils;

public class FellowRecyclerViewAdapter extends XRecyclerAdapter<DynamicBean, FellowRecyclerViewAdapter.NineGridHolder> {


    @NonNull
    @Override
    protected NineGridHolder getViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new NineGridHolder(inflateView(parent, R.layout.dynamic_item));

    }

    @Override
    protected void bindData(@NonNull NineGridHolder holder, int position, DynamicBean item) {
        holder.bind(item);
    }

    @Override
    public int getItemViewType(int position) {
        return NineGridImageView.STYLE_FILL;
    }

    public static class NineGridHolder extends RecyclerView.ViewHolder {
        private NineGridImageView<String> mNglContent;
        private TextView username, createTime,dynamicText,replayNum, praiseNum;
        private ImageView avatar, praiseIcon;


        public NineGridHolder(@NonNull View itemView) {
            super(itemView);
            mNglContent = itemView.findViewById(R.id.dynamic_ngl_images);
            username = itemView.findViewById(R.id.my_dynamic_user_name);
            createTime = itemView.findViewById(R.id.dynamic_item_create_time);
            dynamicText = itemView.findViewById(R.id.dynamic_text);
            replayNum = itemView.findViewById(R.id.dynamic_replay_num);
            praiseNum = itemView.findViewById(R.id.dynamic_praise_num);
            avatar = itemView.findViewById(R.id.my_dynamic_user_Url);
            praiseIcon = itemView.findViewById(R.id.dynamic_praise_icon);

            NineGridImageViewAdapter<String> mAdapter = new NineGridImageViewAdapter<String>() {
                @Override
                protected void onDisplayImage(Context context, ImageView imageView, String s) {
                    Glide.with(imageView.getContext())
                            .load(s)
                            .apply(GlideMediaLoader.getRequestOptions())
                            .listener(new RequestListener<Drawable>() {
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    //这里给图片设置tag，在图片浏览中不展示未加载完成的图片，防止无法退出，一直出于加载中
                                    imageView.setTag("load_success");
                                    return false;
                                }
                            })
                            .into(imageView);
                }

                @Override
                protected ImageView generateImageView(Context context) {
                    return super.generateImageView(context);
                }
            };

            mNglContent.setAdapter(mAdapter);
            mNglContent.setItemImageClickListener((imageView, index, list) -> {

                ImageView currentView = (ImageView) mNglContent.getChildAt(index);
                if (currentView.getTag() == null || !currentView.getTag().equals("load_success")) {
                    Utils.Sout("图片加载中");
                    return;
                }

                List<ImageViewInfo> res = computeBoundsBackward(list);//组成数据
                PreviewBuilder.from((Activity) imageView.getContext())
                        .setImgs(res)
                        .setCurrentIndex(index)
                        .setProgressColor(R.color.zzl_red)
                        .setType(PreviewBuilder.IndicatorType.Dot)
                        .start();//启动
            });



        }
        public void bind(DynamicBean dynamicBean) {
            mNglContent.setImagesData(dynamicBean.getDynamicUrl(), NineGridImageView.NOSPAN);
            username.setText(dynamicBean.getUserName());
            createTime.setText(dynamicBean.getCreateTime());
            dynamicText.setText(dynamicBean.getDynamicText());
            replayNum.setText(String.valueOf(dynamicBean.getComments()));
            praiseNum.setText(String.valueOf(dynamicBean.getLikes()));

            // 已经点赞
            if (dynamicBean.getIsLike().equals(1)) {
                praiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_red_20);
                praiseNum.setTextColor(Color.parseColor("#E54D42"));
            } else {
                praiseIcon.setImageResource(R.drawable.ic_baseline_thumb_up_gray_24);
                praiseNum.setTextColor(Color.parseColor("#8A000000"));
            }

            Glide.with(itemView.getContext())
                    .load(dynamicBean.getUserUrl())
                    .into(avatar);
        }

        /**
         * 查找信息
         * @param list 图片集合
         */
        private List<ImageViewInfo> computeBoundsBackward(List<String> list) {
            List<ImageViewInfo> res = new ArrayList<>();
            for (int i = 0;i < mNglContent.getChildCount(); i++) {
                View itemView = mNglContent.getChildAt(i);
                ImageView thumbView = (ImageView) itemView;

                if (thumbView.getTag() == null || !thumbView.getTag().equals("load_success")) {
                    continue;
                }

                Rect bounds = new Rect();
                if (itemView != null) {
                    thumbView.getGlobalVisibleRect(bounds);
                    //thumbView.getDrawable() ==
                }
                ImageViewInfo info = new ImageViewInfo(list.get(i));
                info.setBounds(bounds);
                res.add(info);
            }

            return res;

        }


    }

}
